package com.cy.store.controller;

import com.cy.store.service.ex.*;
import com.cy.store.util.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;

/**
 * 控制层类的基类
 */
public class BaseController {
    // 操作成功的状态码
    public static final int OK = 200;

    /**
     * @ExceptionHandler用于统一处理抛出的异常--ServiceException.class
     * 请求处理方法，这个方法的返回值是需要传递给前端的数据
     * 自动将异常对象传递给此方法的参数列表上
     * 当项目中产生异常，会被统一拦截到此方法中，这个方法此时就充当请求处理方法，方法的返回值直接返回前端
     */
    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> handleException(Throwable e){
        JsonResult<Void> result = new JsonResult<>(e);
        if(e instanceof UsernameDuplicatedException){
            result.setState(4000);
            result.setMessage("用户名被占用");
        } else if (e instanceof InsertException) {
            result.setState(5000);
            result.setMessage("注册时产生未知异常");
        }else if (e instanceof UserNotFoundException) {
            result.setState(5001);
            result.setMessage("未找到用户");
        }else if (e instanceof PasswordNotMatchException) {
            result.setState(5002);
            result.setMessage("密码错误");
        }else if (e instanceof UpdateException) {
            result.setState(5003);
            result.setMessage("更新时产生未知异常");
        }else if (e instanceof AddressCountLimitException) {
            result.setState(7001);
            result.setMessage("用户收货地址达到上限");
        }else if (e instanceof AddressNotFoundException) {
            result.setState(7002);
            result.setMessage("收货地址不存在异常");
        }else if (e instanceof AccessDeniedException) {
            result.setState(7003);
            result.setMessage("用户收货地址达到上限");
        }else if (e instanceof DeleteException) {
            result.setState(7004);
            result.setMessage("用户收货地址删除异常");
        }else if (e instanceof ProductNotFoundException) {
            result.setState(7005);
            result.setMessage("未找到商品");
        }else if (e instanceof CartNotFoundException) {
            result.setState(8001);
            result.setMessage("未找到购物车数据");
        }
        return result;
    }

    /**
     * 获取用户的uid
     * @param session
     * @return
     */
    protected final Integer getUidFromSession(HttpSession session){
        return Integer.valueOf(session.getAttribute("uid").toString());
    }

    /**
     * 获取当前用户的用户名
     * @param session
     * @return
     */
    protected final String getUsernameFromSession(HttpSession session){
        return session.getAttribute("username").toString();
    }
}
